package com.example.tabbar.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.tabbar.R
import com.example.tabbar.databinding.FragmentAccountBinding


class AccountFragment : Fragment() {
    private var binding: FragmentAccountBinding? = null
    private var user: TextView? = null
    private var role: TextView? = null
    private var userFragment: UserFragment? = null
    private var roleFragment: RoleFragment? = null
    private var currentChildFragment: Fragment? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentAccountBinding.inflate(inflater, container, false)
        return binding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        user = binding!!.user
        role = binding!!.role
        user?.isSelected= true

        setupInitialFragment(savedInstanceState)

        user?.setOnClickListener {
            user?.isSelected= true
            role?.isSelected= false
            switch(0)

        }
        role?.setOnClickListener {
            role?.isSelected= true
            user?.isSelected= false
            switch(1)
        }

        // 添加 add 按钮点击事件
        binding?.add?.setOnClickListener {
            handleAddButtonClick()
        }
    }

    private fun handleAddButtonClick() {
        when {
            user?.isSelected == true -> {
                // 当前在用户页面，跳转到新建用户页面
                (currentChildFragment as? UserFragment)?.let { userFragment ->
                    // 创建新建用户Fragment并传递给UserFragment处理
                    val addUserFragment = EditUserFragment.newInstance()
                    userFragment.loadFragment(addUserFragment)
                    // 立即更新按钮状态
                    binding?.add?.post {
                        updateAddButtonVisibility()
                    }
                }
            }
            role?.isSelected == true -> {
                // 当前在角色页面，跳转到新建角色页面
                (currentChildFragment as? RoleFragment)?.let { roleFragment ->
                    // 创建新建角色Fragment并传递给RoleFragment处理
                    val addRoleFragment = EditRoleFragment.newInstance()
                    roleFragment.loadFragment(addRoleFragment)
                    // 立即更新按钮状态
                    binding?.add?.post {
                        updateAddButtonVisibility()
                    }
                }
            }
        }
    }

    private fun setupInitialFragment(savedInstanceState: Bundle?) {
        if (savedInstanceState == null) {
            userFragment = UserFragment.newInstance()
            childFragmentManager
                .beginTransaction()
                .add(R.id.account_content,userFragment!!,UserFragment::class.java.simpleName)
                .commit()
            currentChildFragment = userFragment
        }else {
            userFragment = childFragmentManager.findFragmentByTag(UserFragment::class.java.simpleName) as UserFragment?
            roleFragment = childFragmentManager.findFragmentByTag(RoleFragment::class.java.simpleName) as RoleFragment?

            // 恢复当前显示的fragment
            userFragment?.let {
                if (!it.isHidden) {
                    currentChildFragment = it
                }
            }

            roleFragment?.let {
                if (!it.isHidden) {
                    currentChildFragment = it
                }
            }
        }

        updateAddButtonVisibility()
    }
    private fun switch(tabIndex: Int) {
        var toShowFragment: Fragment? = null
        when (tabIndex) {
            0 -> {
                if (userFragment == null) {
                    userFragment = UserFragment.newInstance()
                }
                toShowFragment = userFragment
            }
            1 -> {
                if (roleFragment == null) {
                    roleFragment = RoleFragment.newInstance()
                }
                toShowFragment = roleFragment
            }
        }

        // 使用事务正确管理 Fragment 显示
        val transaction = childFragmentManager.beginTransaction()

        // 如果当前 Fragment 存在且不是目标 Fragment，则隐藏它
        currentChildFragment?.let {
            if (it != toShowFragment && !it.isHidden) {
                transaction.hide(it)
            }
        }

        // 处理目标 Fragment
        toShowFragment?.let {
            if (!it.isAdded) {
                // 如果 Fragment 还未添加，则添加它
                transaction.add(R.id.account_content, it, it.javaClass.simpleName)
            } else if(it.isHidden) {
                // 如果 Fragment 已添加，确保它被显示
                transaction.show(it)
            }
        }

        transaction.commit()
        currentChildFragment = toShowFragment

        // 使用 post 确保在 UI 更新完成后执行
        binding?.add?.post {
            updateAddButtonVisibility()
        }
    }
     fun updateAddButtonVisibility() {
        // 检查当前显示的子 fragment
        val visibleFragment = childFragmentManager.fragments.find { !it.isHidden }

        when (visibleFragment) {
            is UserFragment -> {
                // 检查 UserFragment 内部当前显示的 fragment
                val userChildFragment = visibleFragment.childFragmentManager.fragments.find { !it.isHidden }
                binding?.add?.visibility = if (userChildFragment is EditUserFragment || userChildFragment is SetUserFragment) {
                    View.GONE
                } else {
                    View.VISIBLE
                }
            }
            is RoleFragment -> {
                // 检查 RoleFragment 内部当前显示的 fragment
                val roleChildFragment = visibleFragment.childFragmentManager.fragments.find { !it.isHidden }
                binding?.add?.visibility = if (roleChildFragment is EditRoleFragment) {
                    View.GONE
                } else {
                    View.VISIBLE
                }
            }
            else -> {
                binding?.add?.visibility = View.VISIBLE
            }
        }
    }

    @SuppressLint("StaticFieldLeak")
    companion object {
        @Volatile
        private var instance: AccountFragment? = null

        @JvmStatic
        fun newInstance(): AccountFragment =
            instance ?: synchronized(this) {
                instance ?: AccountFragment().apply {
                    arguments = Bundle().apply {}
                }.also { instance = it }
            }
    }
}